<template>
  <div
    id="talkcloudImport"
    class="dialog animated"
    :class="open? 'fadeIn':'fadeOut'"
    v-show="show"
    :style="{visibility: (visible?'visible':'hidden')}"
  >
    <div class="panel animated" :class="open ? 'zoomIn' : ''">
      <div class="title">
        新增资源
        <div class="close" @click="uploadCancel()"></div>
      </div>
      <div class="upload">
        <div class="uploadcontent">
          <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
          >
            <el-menu-item index="1" style="width:50%;text-align: center;">
              <span class="spanlabel">资源上传</span>
            </el-menu-item>
            <el-menu-item index="2" style="width:50%;text-align: center;">
              <span class="spanlabel">H5课件URL</span>
            </el-menu-item>
          </el-menu>

          <div class="uploadfile" v-if="activeIndex==1">
            <!--<span class="spanlabel">资源上传</span><br>-->
            <span class="upload-box">
              <span @click="upload(1)" class="uploadbtn">选择资源</span>
              <input id="file" hidden ref="uploadfile" type="file" name="file"  accept=".pdf" />
            </span>
            <span>{{filename}}</span>
            <!--<div @click="updatedefaultfile" :class="checked?'checkyes':'checkno'">{{filename}}</div>-->
          </div>
          <div class="uploadurl" v-else-if="activeIndex==2">
            <!--<span class="spanlabel">H5课件URL</span><br>-->
            <span class="upload-box">
              <el-input v-model="h5filename" placeholder="请输入H5课件名称" style="width:100%;"></el-input>
            </span>
            <span class="upload-box">
              <el-input
                v-model="fileurl"
                placeholder="请输入H5课件URL,以http://或https://开头"
                style="width:100%;"
              ></el-input>
              <div></div>
            </span>
          </div>
        </div>
        <div class="btnPanel">
          <div class="btnOk" @click="uploadOk">确定</div>
          <div style="width:0.2rem;"></div>
          <div class="btnCancel" @click="uploadCancel">取消</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
var vm, $file;
export default {
  data: function() {
    return {
      show: false,
      open: false,
      visible: false,
      loading: null,
      resourceParentId: "",
      talkConfig: null, //拓课云配置
      uploadsource: false,
      h5filename: "", //h5课件地址名称
      fileurl: "", //上传文件url
      filename: "", //待上传文件名称
      fileSize: "",
      uploadprogress: 0, //上传进度
      activeIndex: "1", //1.为上传文件2.上传url
      checked: false //是否为默认课件
    };
  },
  methods: {
    init: function(data) {
      vm.show = true;
      setTimeout(function() {
        vm.open = true;
        vm.visible = true;
      }, 50);

      vm.resourceParentId = data.resourceParentId;
      if (!vm.talkConfig) {
        //获取拓课云配置
        api.getTalkYunConfig().then(function(data) {
          vm.talkConfig = data.info;
        });
      }
    },
    cancel: function() {
      //隐藏弹窗
      vm.open = false;

      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
      }, 500);
    },
    /**
     * 添加资源
     */
    uploadFile() {
      console.log($file);
      const file = $file[0].files[0];
      if (!file) {
        alert("请选择文件");
        return;
      }

      vm.filename = file.name;
      console.log(vm.filename);
      vm.fileSize = file.size;
      //   let roomid = Number(vm.currentRow.talkcloudRoomId);
      vm.filedata = new FormData(); //创建form对象
      vm.filedata.append("file", file); //通过append向form对象添加数据
      vm.filedata.append("key", vm.talkConfig.key); //企业ID
      vm.filedata.append("conversion", 1); //是否转换
      vm.filedata.append("isopen", 1); //是否公开文档
      //   vm.filedata.append("serial", roomid); //房间号
      vm.filedata.append("dynamicppt", 0); //0是否是非动态ppt 1是动态ppt
    },
    /**
     * 上传调用
     */
    upload(index) {
      if (!$file) {
        $file = $("#file");
        $file[0].accept = ".xls,.xlsx,.ppt;*.pptx;*.doc;*.docx;*.txt;*.rtf;*.pdf;*.jpg;*.gif;*.jpeg;*.png;*.bmp;*.flv;*.mp3;*.mp4;*.zip"; 
        $file.change(function() {
          vm.uploadFile();
        });
      }
      $file.val("");
      $file.click();
      // if (index == 1) {
      //   //文件上传
      //   this.$refs.uploadfile.dispatchEvent(new MouseEvent("click"));
      // } else if (index == 2) {
      //   //url上传
      // }
    },
    resourceSave(fileid) {
      console.log(fileid);
      var param = new FormData();
      param.append("talkcloudFileId", fileid + "");
      param.append("resourceParentId", vm.resourceParentId);
      param.append("resourceName", vm.filename);
      param.append("resourceSize", vm.fileSize);
      api.resourceAdd(param).then(function(data) {
        if (data.resultCode == 2000) {
          tool.message({
            showClose: true,
            message: "上传成功",
            type: "success"
          });
          vm.uploadCancel();
        } else {
          vm.$message.error(data.message);
          vm.uploadCancel();
        }
      });
    },
    /**
     * 确认上传
     */
    uploadOk() {
      let configfile = {
        //上传文件
        headers: { "Content-Type": "multipart/form-data" },
        timeout: 2000000,
        baseURL: vm.talkConfig.url,
        withCredentials: false,
        onUploadProgress: uploadProgress
      };
      let configurl = {
        //上传url
        headers: { "Content-Type": "multipart/form-data" },
        baseURL: vm.talkConfig.url,
        withCredentials: false
      };

      function uploadProgress(progressEvent) {
        //上传进度回调
        let progress = progressEvent;
        let loaded = progress.loaded;
        let total = progress.total;
        let rate = (loaded / total).toFixed(2) * 100;
        rate = Math.round(rate * 100) / 100;
        vm.uploadprogress = rate;

        vm.$nextTick(function() {
          //dom更新完毕回调
          $(".el-loading-text").text(
            "正在上传 " + vm.filename + " ，已上传" + vm.uploadprogress + "%"
          );
        });
      }

      if (vm.activeIndex == "1") {
        //资源上传

        if (vm.filedata != null) {
          //判断是否上传文件
          vm.loading = this.$loading({
            lock: true,
            text:
              "正在上传 " + vm.filename + " ，已上传" + vm.uploadprogress + "%",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
          });
          uploadtalkyun();
        } else {
          vm.$message({
            message: "请选择文件",
            type: "warning"
          });
        }
      } else if (vm.activeIndex == "2") {
        //h5url上传
        if (vm.fileurl != "") {
          //判断是否上传url
          uploadurl();
        } else {
          vm.$message({
            message: "请输入h5课件URL",
            type: "warning"
          });
        }
      }

      function uploadtalkyun() {
        //上传文件
        console.log(vm.filedata);
        api
          .uploadTalkCloud(vm.filedata, configfile)
          .then(function(data) {
            vm.loading.close();
            console.log(data);
            if (data.result != 0) {
              vm.$message({
                message: "暂不支持该文件上传！",
                type: "error"
              });
              return;
            }
            vm.resourceSave(data.fileid);
          })
          .catch(function(errdata) {
            vm.loading.close();
            vm.$message({
              message: "上传资源失败,请联系管理员！",
              type: "error"
            });
            vm.uploadCancel();
          });
      }

      function uploadurl() {
        //上传url

        var param = new FormData();
        param.append("bosResourceUrl", vm.fileurl);
        param.append("resourceParentId", vm.resourceParentId);
        param.append("resourceName", vm.h5filename + ".url");
        param.append("resourceSize", 0);
        api.resourceAdd(param).then(function(data) {
          if (data.resultCode == 2000) {
            tool.message({
              showClose: true,
              message: "上传成功",
              type: "success"
            });
            vm.uploadCancel();
          } else {
            vm.$message.error(data.message);
            vm.uploadCancel();
          }
        });
      }
    },
    /**
     * 取消上传
     */
    uploadCancel() {
      vm.uploadsource = false;
      vm.filedata = null;
      vm.fileurl = "";
      vm.filename = "";
      vm.fileSize = "";
      vm.h5filename = "";
      vm.checked = false;
      //隐藏弹窗
      vm.open = false;
      if ($file) {
        //清空文件名和文件输入框
        $file.val("");
        $file = null;
      }
      setTimeout(function() {
        vm.show = false;
        vm.visible = false;
      }, 500);
      vm.$emit("callback");
    },
    /**
     *上传选项
     */
    handleSelect(key, keyPath) {
      vm.activeIndex = key + "";
    }
  },
  mounted: function() {},
  created: function() {
    vm = this;
  }
};
</script>
<style scoped src="@/style/module/dialog.css"></style>
<style lang="scss">
#talkcloudImport {
  .upload {
    width: 100%;
    height: 3rem;
    .title {
      width: 100%;
      height: 0.5rem;
      line-height: 0.5rem;
      padding: 0rem 0.3rem;
      font-size: 0.2rem;
      font-weight: bold;
      color: #333333;
    }
    .uploadcontent {
      width: 100%;
      height: 1.5rem;
      padding: 0rem 0.3rem;
      .uploadfile {
        width: 100%;
        height: 0.75rem;
        line-height: 1rem;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        .upload-box {
          .uploadbtn {
            padding: 0.08rem 0.5rem;
            color: #ffffff;
            cursor: pointer;
            width: 1rem;
            height: 0.36rem;
            background: #5f9df9;
            border-radius: 0.05rem;
          }
          .file {
            position: relative;
            background: #d0eeff;
            border: 1px solid #99d3f5;
            border-radius: 0.3rem;
            overflow: hidden;
            color: rgb(0, 148, 255);
            text-decoration: none;
            text-indent: 0;
            line-height: 20px;
            background: none;
            border: none;
          }
          .file input {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
            opacity: 0;
          }
        }
      }
      .uploadurl {
        width: 100%;
        height: 0.75rem;
        line-height: 0.6rem;
        .upload-box {
          .el-input__inner {
            border-radius: 0.05rem;
            font-size: 0.16rem;
            color: #666666;
            height: 0.36rem !important;
            line-height: 0.36rem;
          }
        }
      }
    }
    .btnPanel {
      width: 100%;
      height: 1rem;
      display: inline-flex;
      line-height: 1rem;
      justify-content: center;
      align-items: center;
      .btnOk {
        width: 1.6rem;
        height: 0.4rem;
        font-size: 0.16rem;
        background: #3885f8;
        color: #ffffff;
        border-radius: 0.1rem;
        line-height: 0.4rem;
        text-align: center;
        cursor: pointer;
      }
      .btnOk:hover {
        background: rgba(56, 133, 248, 0.8);
      }
      .btnCancel {
        width: 1.6rem;
        height: 0.4rem;
        font-size: 0.16rem;
        background: #ffffff;
        border-radius: 0.1rem;
        color: #333333;
        border: 0.01rem solid #c0c4cc;
        line-height: 0.4rem;
        text-align: center;
        cursor: pointer;
      }
      .btnCancel:hover {
        background: rgba(56, 133, 248, 0.1);
      }
    }
  }
}
</style>
<style scoped>
.panel {
  width: 8rem;
}
</style>
